package main.java.com.lee.thread;

import java.util.concurrent.*;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/12/8
 */
public class ThreadUtil {

	public static void shutdownThreadPoolGracefully(ThreadPoolExecutor executor) throws InterruptedException {
		if (!(executor instanceof ExecutorService) || executor.isTerminated()) {
			return;
		}

		executor.shutdown();

		if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
			executor.shutdownNow();
		}

		try {
			if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
				System.out.println("未正常结束");
			}
		} catch (InterruptedException e) {
			executor.shutdownNow();
		}

		if(!executor.isTerminated()) {
			try  {
				for (int i = 0; i < 1000; i++) {//循环关闭1000次，每次等待10毫秒
					System.out.println("第: " + i + "次关闭");
					if (executor.awaitTermination(10, TimeUnit.MILLISECONDS)) {
						break;
					}
					executor.shutdownNow();
				}} catch (InterruptedException e)  {
				System.err.println(e.getMessage());
			} catch (Throwable e)  {
				System.err.println(e.getMessage());
			}
		}
	}


	static class SeqOrScheduledTargetThreadPoolLazyHolder{
		static final ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory());
		static {
			Runtime.getRuntime().addShutdownHook(new Thread(()->{
				System.out.println("系统要退出了");
				try {
					shutdownThreadPoolGracefully(EXECUTOR);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}));
		}
	}
}
